<script setup>
import { ref, watch, onMounted } from 'vue'
import { getAllCity } from "@/api/City/AllCity";
import { useCityStore } from "@/stores/city";
import { useRouter } from "vue-router";
import MyCityBtn from './MyCityBtn.vue';
import MyCityList from './MyCityList.vue';
const cityList = ref([]);
const searchInput = ref('')
const searchCities = ref([])
const cityStore = useCityStore();
const router = useRouter();
onMounted(async () => {
    cityList.value = await getAllCity();

});


watch(searchInput, (val) => {
    console.log(val)
    //let list =cityList.value
    searchCities.value = []
    for (let item in cityList.value) {
        //console.log(item)
        let list = cityList.value[item]
       // console.log(list)
        let newList = list.filter(item => {
            return item.name.includes(val)||item.spell.includes(val)
        })
        //数组合并
        searchCities.value = searchCities.value.concat(newList)
    }
    console.log(searchCities.value)
})
function handleClick(name) {
    cityStore.setNowCity(name);
    cityStore.addCityList(name);
    router.push("/");

}
</script>
<template>
    <div class="city-view">
        <el-card style="width: 50%;margin: 0 auto; ">
            <div class="city-view-header">
                <div class="search">
                    <img src="@/assets/images/搜索.png" alt="" />
                    <input type="text" placeholder="请输入搜索城市" v-model="searchInput">
                </div>
            </div>

            <div class="city-view-body">
                <div v-if="searchInput">
                    <div v-if="searchCities.length > 0">
                        <van-cell v-for="city in searchCities" :key="city.id" :title="city.name" class="city-cell"
                            @click="handleClick(city.name)" />
                    </div>
                    <div v-else>
                        <van-cell title="没有找到相关城市" />
                    </div>
                </div>
                <div v-else>
                    <MyCityBtn></MyCityBtn>
                    <MyCityList :cityList="cityList"></MyCityList>
                </div>
            </div>
        </el-card>
    </div>
</template> 
<style scoped>
.city-view-header {
    display: flex;
    justify-content: center;
    align-items: center;
}

.search {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    padding: 10px;
    background-color: #eee;
    border-radius: 10px;
}

.search img {
    width: 20px;
    height: 20px;
    margin-right: 10px;
}

.search input {
    width: 100%;
    padding: 5px;
    border: none;

    border-radius: 5px;
    background-color: #eee;
    font-size: 16px;
    outline: none;
}
.city-cell:hover {
    background-color: #f2f2f2;
}
</style>